package proxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class HTTPResponseWrapper {
	private HashMap<String, ArrayList<String>> headers = new HashMap<String, ArrayList<String>>();
	private String responseCode = "";
	private String responseMessage = "";
	private String protocol = "";
	private byte[] responseBytes;
	
	public HTTPResponseWrapper(byte[] response){
		parseRequest(response);
	}
	
	public HTTPResponseWrapper(){}
	
	public void parseRequest(byte[] response){
		responseBytes = response;
		
		String responseString = new String(response);
		String headerLines = responseString.split("\r\n\r\n")[0];
		
		String[] lines = headerLines.split("\r\n");
		
		String[] parts = lines[0].split(" ", 3);
		protocol = parts[0];
		responseCode = parts[1];
		responseMessage = parts[2];
		
		//Parse the headers
		for (int i = 1; i < lines.length; i++) {
			parts = lines[i].split(":", 2);
			ArrayList<String> vals = headers.get(parts[0].trim());
			if(vals == null) {
				vals = new ArrayList<String>();
				headers.put(parts[0].trim(), vals);
			}
			
			vals.add(parts[1].trim());
		}
	}
	
	public String getHeader(String key){
		ArrayList<String> vals = headers.get(key);
		if(vals == null) return "";
		return vals.get(vals.size() - 1);
	}
	
	public ArrayList<String> getHeaders(String key){
		return headers.get(key);
	}
	
	public Set<String> getAllHeadersName(){
		return headers.keySet();
	}
	
	public String getResponseCode(){
		return responseCode;
	}
	
	public String getProtocol(){
		return protocol;
	}
	
	public String getResponseMessage(){
		return responseMessage;
	}
	
	public String toString(){
		String result = getProtocol() + " " + getResponseCode() + " " + getResponseMessage() + "\n";
		for (String key : headers.keySet()) {
			for (String val : headers.get(key)) {
				result = result.concat(key + ": " + val + "\n");
			}
		}
		
		return result;
	}
	
	public byte[] getResponseBytes(){
		return responseBytes;
	}
}
